package cn.wolfcode.luowowo.website.resolver;

import cn.wolfcode.luowowo.cache.service.IRedisService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.web.annotation.GetUserInfoAnnotation;
import cn.wolfcode.luowowo.website.web.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInfoResolver implements HandlerMethodArgumentResolver {

    @Reference
    private IRedisService redisService;

    //第一个方法,检测指定参数类型,返回true则进入第二个方法进行解析操作
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType() == UserInfo.class &&
                methodParameter.hasParameterAnnotation(GetUserInfoAnnotation.class);
    }

    //第二个方法,解析参数,说白就是自己操作处理方法形参中数据的设置,覆盖spring帮我们解析的操作
    //有个问题,一旦指定了解析操作,页面传过来的数据还能像从前那样这正常赋值到映射对象中(处理方法形参)去吗
    //自定义解析操作相当于将一条路开辟成两条路,自定义那条是大路,原来那条则被淹没了,如何告诉spring带数据往哪走
    //设置路标(即注解),注解时java唯一具有形象的识别功能的工具,利用它来指引数据的走向
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        UserInfo userInfo = null;
        String token = CookieUtil.getToken(request, response);
        if (token != null) {
            userInfo = redisService.getValueByToken(token);
        }
        if (userInfo == null) {
            //throw new LogicException("您还没登录,请先登录再操作");
            return null;
        }
        return userInfo;
    }
}
